#%%
import pandas as pd

#%%
def highlow_sortter(lists):
    if len(lists) % 2 == 0:
        cutF = int(len(lists) / 2)
        x = [lists[:cutF], lists[cutF:]]
    else:
        cutF = int(len(lists) / 2)
        x = [lists[:cutF], lists[cutF:]]
    while True:
        b = []
        for a in x:
            if len(a) > 1:
                min_ind = a.index(min(a))
                max_ind = a.index(max(a))
                if (
                    (min_ind == 0 and max_ind == len(a))
                    or (max_ind == 0 and min_ind == len(a))
                    or min_ind == max_ind
                ):

                    b.append(a)
                    continue
                elif (
                    min_ind == 0
                    or max_ind == 0
                    or max_ind == len(a)
                    or min_ind == len(a)
                ):
                    if min_ind == 0 or max_ind == 0:
                        if min_ind == 0:
                            cutter = max_ind
                        elif max_ind == 0:
                            cutter = min_ind
                        l2 = a[cutter + 1 :]
                        l1 = a[: cutter + 1]
                        nl = [l1, l2]

                    elif max_ind == len(a) or min_ind == len(a):
                        if min_ind == len(a):
                            cutter = max_ind
                        elif max_ind == len(a):
                            cutter = min_ind
                        l1 = a[cutter + 1 :]
                        l2 = a[: cutter + 1]
                        nl = [l1, l2]

                else:
                    if min_ind > max_ind:
                        l3 = a[min_ind:]
                        l2 = a[max_ind:min_ind]
                        l1 = a[:max_ind]

                    elif min_ind < max_ind:
                        l3 = a[max_ind:]
                        l2 = a[min_ind:max_ind]
                        l1 = a[:min_ind]

                    nl = [l1, l2, l3]

                nl2 = []
                for c in nl:
                    if len(nl[0]) == 1 and nl.index(c) == 0:
                        nl2.append(c)
                    elif len(c) == 1:
                        nl2[-1].extend(c)
                    elif c != []:
                        nl2.append(c)
                b.extend(nl2)
            else:
                b.append(a)
        if x == b:
            break
        x = b
    return x


#%%
df = pd.read_csv("300999.csv")
df = df[["date", "close"]]
dic = df.to_dict(orient="list")
l = highlow_sortter(dic["close"])
totalLens = 0

for x in l:
    lens = len(x)
    preLens = totalLens
    totalLens += lens
    dataL = dic["date"][preLens:totalLens]
    temp = {"date": dataL, "data": x}
    df = pd.DataFrame(temp)
    if x[0] > x[-1]:
        distion = -1
    elif x[0] < x[-1]:
        distion = 1
    df["distion"] = distion
    print(df)


# %%
